package edu.utexas.mapreduce;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.List;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

public class HttpStatusRequestHandler implements HttpHandler {

	// SS: local view of sState
	private SharedMapState sState = null;
	
	// SS: constructor
	public HttpStatusRequestHandler(SharedMapState sharedState) {
		this.sState = sharedState;
	}
	
	String getJobStatus(Integer jobID) {
		
		JobThread job = sState.getJobThread(jobID);
		if (job == null) {
			return "JOB " + jobID + " NOT FOUND";
		}
		return job.getJobState().toString();
	}
	
	String getResponse(URI uri) {
		String query = uri.getQuery();
		if (query == null) {
			List<Integer> jobIDs = sState.getJobIDs();
			StringBuilder sb = new StringBuilder();
			sb.append("<html><pre>");
			sb.append("registered jobs:\n");
			for (Integer jobID : jobIDs) {
				sb.append("<a href=\"" +uri.toString() + "?" + jobID + "\">JOB " + jobID + "</a>\n");
			}
			sb.append("</pre></html>");
			return sb.toString();
		}
		return getJobStatus(new Integer(query));
	}
	
	public void handle(HttpExchange httpEx) throws IOException {
		String response = getResponse(httpEx.getRequestURI());
	    httpEx.sendResponseHeaders(200, response.length());
        OutputStream os = httpEx.getResponseBody();
        os.write(response.getBytes());
        os.close();
	}

}
